import os
from os import environ
import captcha
import logging
import datetime
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db

PAGESIZE = 10

class Log(db.Model):
  comment = db.StringProperty()
  name =  db.StringProperty()
  category = db.IntegerProperty(default=0)
  scategory = db.StringProperty()
  scolor = db.StringProperty()
  pinlabel =  db.StringProperty()
  when =  db.StringProperty()
  created = db.DateTimeProperty(auto_now_add=True)
  imageindex = db.IntegerProperty(default=0)
  deleteRequested = db.BooleanProperty(default=False)

class Group(db.Model):
    date = db.DateTimeProperty(auto_now_add=True)
    center_lat = db.FloatProperty()
    center_lng = db.FloatProperty()
    marker_lat = db.FloatProperty()
    marker_lng = db.FloatProperty()
    zoom = db.IntegerProperty(default=2)
    place = db.StringProperty()
    people = db.StringProperty('neighbors')
    contact =  db.StringProperty()
    moreinfo =  db.StringProperty()
    moreinfoLog =  db.StringProperty(default='')
    moreinfoImage =  db.StringProperty(default='')
    activity =  db.StringProperty(default='live')
    activityLog =  db.StringProperty(default='know')
    user = db.UserProperty()
    mapdefined = db.BooleanProperty(default=False)
    countLog = db.IntegerProperty(default=0) 
    imageLog = db.IntegerProperty(default=0)
    category = db.StringListProperty(default=["typical special"])
    categoryLog = db.StringListProperty(default=["typical special"])
    categoryImage = db.StringListProperty(default=["typical special"])
    color = db.StringListProperty(default=["ff0000 ffff00"])
    colorLog = db.StringListProperty(default=["ff0000 ffff00"])
    colorImage = db.StringListProperty(default=["ff0000 ffff00"])
    pagesizeLog = db.IntegerProperty(default=10)
    geoboxes = db.StringListProperty()
    prevgroup =  db.StringProperty(default='')
    nextgroup =  db.StringProperty(default='')
    acrossgroup =  db.StringProperty(default='')
    pintext =  db.StringProperty(default='Name')
    
class Pin(db.Model):
    date = db.DateTimeProperty(auto_now_add=True)
    lat = db.FloatProperty()
    lng = db.FloatProperty()
    name = db.StringProperty()
    cornerColor	 = db.StringProperty(default='ffffff')
    height = db.IntegerProperty(default=32)
    label = db.StringProperty(default='')
    labelColor = db.StringProperty(default='000000')
    labelSize = db.IntegerProperty(default=2)
    primaryColor = db.StringProperty(default='ff0000')
    shadowColor = db.StringProperty(default='000000')
    shape = db.StringProperty(default='circle')
    strokeColor = db.StringProperty(default='000000')
    width = db.IntegerProperty(default=32)
    category = db.IntegerProperty(default=0)
    scategory = db.StringProperty()
    logindex = db.IntegerProperty(default=0)
    imageindex = db.IntegerProperty(default=0)

class nextMainPage(webapp.RequestHandler):
    def get(self):
        place_id = self.request.get("place", None)
        nextplace_id = self.request.get("nextplace", None)
        user = users.get_current_user()
        if place_id is None: #no place has been set by the user
            path = os.path.join(os.path.dirname(__file__), 'choose_placenextprev.html')
            if user: #offer user or nonuser options back at choose.html
                url = users.create_logout_url(self.request.uri)
                url_linktext = 'Signout'
                url_linktextmore = ' if you wish. You will be returned to this page after you signout. <b>Supply a name. </b>'
            else:
                url = users.create_login_url(self.request.uri)
                url_linktext = 'Signin'
                url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
            template_values = {
                'url': url,
                'url_linktext': url_linktext,
                'url_linktextmore': url_linktextmore,
                }
            self.response.out.write(template.render(path, template_values))
        if prevplace_id is None and nextplace_id is None: #no place has been set by the user
            path = os.path.join(os.path.dirname(__file__), 'choose_placenextprev.html')
            if user: #offer user or nonuser options back at choose.html
                url = users.create_logout_url(self.request.uri)
                url_linktext = 'Signout'
                url_linktextmore = ' if you wish. You will be returned to this page after you signout.'
            else:
                url = users.create_login_url(self.request.uri)
                url_linktext = 'Signin'
                url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
            template_values = {
                'url': url,
                'url_linktext': url_linktext,
                'url_linktextmore': url_linktextmore,
                }
            self.response.out.write(template.render(path, template_values))
        else: #some place has been set by the person (may be user)
            #so pull up information on the place set by the person
            key = db.Key.from_path("Group", place_id)
            place = Group.get(key)
            #determine if place exists already
            #because choose_place.html has produced a desired place name
            #or because user has supplied a place name with ?...
            if not place: #person's place does NOT exist already
                path = os.path.join(os.path.dirname(__file__), 'choose_placenextprev.html')
                if user: #offer user or nonuser options back at choose.html
                    url = users.create_logout_url(self.request.uri)
                    url_linktext = 'Signout'
                    url_linktextmore = ' if you wish. You will be returned to this page after you signout. <b>The current place must already exist. </b>'
                else:
                    url = users.create_login_url(self.request.uri)
                    url_linktext = 'Signin'
                    url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
                template_values = {
                    'url': url,
                    'url_linktext': url_linktext,
                    'url_linktextmore': url_linktextmore,
                    }
                self.response.out.write(template.render(path, template_values))
                
        if prevplace_id is None: #next place has been set by the user
            maptemplate_values = dict(place_id=place.key(), prevgroup=place.place, 
                people=place.people, center_lat=place.center_lat, 
                center_lng=place.center_lng, map_zoom=place.zoom,
                marker_lat=place.marker_lat, marker_lng=place.marker_lng, 
                contact=place.contact, moreinfo=place.moreinfo,
                nextgroup=place.nextgroup, place=nextplace_id,
                acrossgroup=place.nextgroup, pintext=place.pintext,
                category=place.category, color=place.color,
                mapdefined=place.mapdefined,
                countLog=place.countLog,
                activity=place.activity, user=user)
            if place.mapdefined: #person's place exists as a map
                if user: #user is owner and may revise the existing map
                    template_values = maptemplate_values
                    path = os.path.join(os.path.dirname(__file__), 'add_mapnext.html')
                    self.response.out.write(template.render(path, template_values))
            else: #no original map defined, send back to choose
                path = os.path.join(os.path.dirname(__file__), 'choose_placenextprev.html')
                if user: #offer user or nonuser options back at choose.html
                    url = users.create_logout_url(self.request.uri)
                    url_linktext = 'Signout'
                    url_linktextmore = ' if you wish. You will be
                    returned to this page after you signout. <b>Supply either a next or previous name. </b>'
                else:
                    url = users.create_login_url(self.request.uri)
                    url_linktext = 'Signin'
                    url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
                template_values = {
                    'url': url,
                    'url_linktext': url_linktext,
                    'url_linktextmore': url_linktextmore,
                    }
                self.response.out.write(template.render(path, template_values))
        else: #prev place has been set by the user
            maptemplate_values = dict(place_id=place.key(), nextgroup=place.place, 
                people=place.people, center_lat=place.center_lat, 
                center_lng=place.center_lng, map_zoom=place.zoom,
                marker_lat=place.marker_lat, marker_lng=place.marker_lng, 
                contact=place.contact, moreinfo=place.moreinfo,
                prevgroup=place.prevgroup, place=prevplace_id,
                acrossgroup=place.nextgroup, pintext=place.pintext,
                category=place.category, color=place.color,
                mapdefined=place.mapdefined,
                countLog=place.countLog,
                activity=place.activity, user=user)
            if place.mapdefined: #person's place exists as a map
                if user: #user is owner and may revise the existing map
                    template_values = maptemplate_values
                    path = os.path.join(os.path.dirname(__file__), 'add_mapnext.html')
                    self.response.out.write(template.render(path, template_values))
            else: #no original map defined, send back to choose
                path = os.path.join(os.path.dirname(__file__), 'choose_placenextprev.html')
                if user: #offer user or nonuser options back at choose.html
                    url = users.create_logout_url(self.request.uri)
                    url_linktext = 'Signout'
                    url_linktextmore = ' if you wish. You will be
                    returned to this page after you signout. <b>Supply either a next or previous name. </b>'
                else:
                    url = users.create_login_url(self.request.uri)
                    url_linktext = 'Signin'
                    url_linktextmore = ' if you will be creating a map for your group. You will be returned to this page after you signin.'
                template_values = {
                    'url': url,
                    'url_linktext': url_linktext,
                    'url_linktextmore': url_linktextmore,
                    }
                self.response.out.write(template.render(path, template_values))
                    

class nextLogMainPage(webapp.RequestHandler):
    def get(self):
        place_id = self.request.get("place", None)
        user = users.get_current_user()
        logging.info("nestLog place_id1 %s " % place_id)
        key = db.Key.from_path("Group", place_id)
        place = Group.get(key)
        logtemplate_values = dict(place_id=place.key(), prevgroup=place.place, 
            people=place.people, 
            contact=place.contact, moreinfo=place.moreinfoLog,
            category=place.categoryLog, color=place.colorLog,
            nextgroup=place.nextgroup, place=place.nextgroup,
            acrossgroup=acrossplace_id, pintext=place.pintext,
            mapdefined=place.mapdefined,
            countLog=place.countLog, 
            activity=place.activityLog, user=user)
        place.activityLog = place.activity
        place.moreinfoLog = place.moreinfo
        place.colorLog = place.color
        place.categoryLog = place.category
        place.prevgroupLog = place.prevgroup
        place.nextgroupLog = place.nextgroup
        place.acrossgroupLog = place.acrossgroup
        place.countLog += 1
        place.put()
        template_values = dict(place_id=place.key(), place=place.place, 
            people=place.people, 
            contact=place.contact, moreinfo=place.moreinfoLog,
            category=place.categoryLog, color=place.colorLog,
            nextgroup=place.nextgroup, nextgroup=place.nextgroup,
            acrossgroup=place.acrossplace, pintext=place.pintext,
            mapdefined=place.mapdefined,
            countLog=place.countLog,
            activity=place.activityLog, user=user)
        path = os.path.join(os.path.dirname(__file__), 'add_lognext.html')
        self.response.out.write(template.render(path, template_values))

class AddMapnext(webapp.RequestHandler):
    #creates group 
    def get(self):
        place_id = self.request.get('place')
        group = Group(key_name=place_id)
        group.place = place_id
        group.center_lat = float(self.request.get('center_lat'))
        group.center_lng = float(self.request.get('center_lng'))
        group.zoom = int(self.request.get('zoom'))
        group.people = self.request.get('people')
        group.contact = self.request.get('contact')
        group.activity = self.request.get('activity')
        group.moreinfo = self.request.get('moreinfo')
        group.prevgroup = self.request.get('prevgroup')
        group.nextgroup = self.request.get('nextgroup')
        group.acrossgroup = self.request.get('acrossgroup')
        group.pintext = self.request.get('pintext')
        group.user = self.request.get('user')
        color = self.request.get('colors')
        group.color = color.split()
        category = self.request.get('categories')
        group.category = category.split()
        group.marker_lat = float(self.request.get('marker_lat'))
        group.marker_lng = float(self.request.get('marker_lng'))
        #this pin should NOT have a parent so it is not
        #included in the many ancestor pins
        pin = Pin(key_name=place_id)
        pin.name = place_id
        pin.lat = float(self.request.get('marker_lat'))
        pin.lng = float(self.request.get('marker_lng'))
        pin.put()
        group.mapdefined = True
        group.put()
        self.redirect("/mainlognext?place=%s" % place_id)
            
class AddLognext(webapp.RequestHandler):
    #creates group 
    def get(self):
        place_id = self.request.get('place')
        group = Group(key_name=place_id)
        group.place = place_id
        group.people = self.request.get('people')
        group.contact = self.request.get('contact')
        group.activityLog = self.request.get('activityLog')
        group.moreinfoLog = self.request.get('moreinfoLog')
        group.prevgroupLog = self.request.get('prevgroupLog')
        group.nextgroupLog = self.request.get('nextgroupLog')
        group.acrossgroupLog = self.request.get('acrossgroupLog')
        group.pintextLog = self.request.get('pintextLog')
        color = self.request.get('colors')
        group.colorLog = color.split()
        category = self.request.get('categories')
        group.categoryLog = category.split()
        #this pin should NOT have a parent so it is not
        #included in the many ancestor pins
        group.put()
        self.redirect("/choose_placenextprev.html")
            
application = webapp.WSGIApplication(
                                     [('/mainaddnext', nextMainPage),
                                      ('/mainlognext', nextLogMainPage),
                                      ('/add_mapnext', AddMapnext),
                                      ('/add_lognext', AddLognext),
                                      ],
                                     debug=True)

                    
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
